/**
 * Server
 */
const Koa = require('koa');
const session = require('koa-session');
const Router = require('koa-router');

const app = new Koa();

// 添加session，目的是写入Cookie
app.keys = ['anrin'];
app.use(session({ key: 'anrin:session' }, app));

// router
const router = new Router();
router.use(async function (ctx, next) {
  ctx.session.user = { user: 'yes' };
  await next();
});

// 简单请求
//
router.get('/simple', function (ctx) {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.body = 'yes';
});

// 非简单请求
//
// 预检请求
router.options('/notSimple', function (ctx) {
  ctx.set({
    'Access-Control-Allow-Origin': ctx.request.header.origin,
    'Access-Control-Allow-Methods': 'OPTIONS, GET, POST',
    'Access-Control-Allow-Headers': 'Content-Type, X-Custom-Header',
    'Access-Control-Max-Age': 3628800,
    'Access-Control-Allow-Credentials': true
  });
  ctx.status = 200;
});
router.all('/notSimple', function (ctx) {
  ctx.set({
    'Access-Control-Allow-Origin': ctx.request.header.origin,
    'Access-Control-Allow-Credentials': true
  });
  ctx.body = 'yes';
});

app.use(router.routes());
app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});
